// Package database @program: account
//@author: edte
//@create: 2021-12-28 09:24
package database

import (
	log2 "account/log"
	"account/tools"
	"context"
	"fmt"

	"errors"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func UserRegisterDb(user tools.User) (err error) {
	mysqlPath := tools.GetEnv("MYSQL_PATH", "localhost:3306")
	mysqlUser := tools.GetEnv("MYSQL_USER", "root")
	mysqlPassword := tools.GetEnv("MYSQL_PASSWORD", "123456")
	db, err := gorm.Open(mysql.Open(mysqlUser+":"+mysqlPassword+"@tcp("+mysqlPath+")/users?charset=utf8&parseTime=True&loc=Local"), &gorm.Config{})

	// db, err := gorm.Open(mysql.Open("root:123456@tcp(localhost:3306)/users?charset=utf8&parseTime=True&loc=Local"), &gorm.Config{})
	if err != nil {

		writeLog, err2 := log2.WriteLog(context.Background(), "account", "UserRegisterDb", user.UserPhone, "Warring", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}

		return errors.New("failed to connect database")
	}
	tmpUser := tools.User{}
	db.Model(&tools.User{}).Where("user_phone = ?", user.UserPhone).First(&tmpUser)
	if tmpUser.Id != 0 {
		writeLog, err2 := log2.WriteLog(context.Background(), "account", "UserRegisterDb", user.UserPhone, "Warring", "The account has been registered")
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return errors.New("the account has been registered")
	}

	db.Model(&tools.User{}).Create(&user)
	db.Model(&tools.User{}).Where("user_phone = ?", user.UserPhone).First(&tmpUser)
	if tmpUser.UserPhone != user.UserPhone || tmpUser.Password != user.Password {
		if tmpUser.UserPhone != user.UserPhone {

			writeLog, err2 := log2.WriteLog(context.Background(), "account", "UserRegisterDb", user.UserPhone, "Warring", "Registration failed,Account verification failed")
			if writeLog == 200 {
				fmt.Println("成功写入日志")
			}
			if err2 != nil {
				fmt.Println("写入日志失败")
			}
		}
		if tmpUser.Password != user.Password {
			writeLog, err2 := log2.WriteLog(context.Background(), "account", "UserRegisterDb", user.UserPhone, "Warring", "Registration failed,Password verification failed")
			if writeLog == 200 {
				fmt.Println("成功写入日志")
			}
			if err2 != nil {
				fmt.Println("写入日志失败")
			}
		}

		return errors.New("registration failed")
	}
	return err
}
